package top.infopub.mgr.flow.web;


import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.generic.GenericController;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.service.FiaProcessManageService;
import top.infopub.mgr.flow.domain.ProcessNodeDomain;
import top.infopub.mgr.flow.service.ProcessNodeService;
import top.infopub.mgr.flow.service.ProcessService;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.service.BidReviewService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.flow.Process;
import top.infopub.model.mkt.BidReview;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 工作审批流相关处理controller
 * @author Awoke
 * @version 2019年12月16日
 * @see FlowProcessController
 * @since
 */
@Controller
@RequestMapping("/flowProcess")
public class FlowProcessController extends GenericController {

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Autowired
    private ProcessNodeService processNodeService;

    @Autowired
    private ProcessService processService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private BidReviewService bidReviewService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Autowired
    private FiaProcessManageService fiaProcessManageService;

    /**
     * 查询 首页-待我审批 列表数据
     * @return
     */
    @RequestMapping("/queryPending")
    @ResponseBody
    public RspVo<ProcessNodeDomain> queryPending(ParamPage paramPage) {
        Page<ProcessNodeDomain> page = new Page<ProcessNodeDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = wsFlowProcess.queryPagePendingProcNodes("", page);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 审批页面跳转
     */
    @RequestMapping("/toDispatch")
    public String toDispatch(HttpServletRequest request, String processId) {
        Process proc = processService.selectByPrimaryKey(processId);
        // 当前审批关联业务表单表名
        String srcBizTable = proc.getSrcBizTable();
        // 当前审批关联业务表记录ID
        String srcBizSguid = proc.getSrcBizSguid();
        // 进行跳转 
        return bizControllerMapping(srcBizTable, srcBizSguid);
    }

    /**
     * 审批 
     */
    @RequestMapping("/dealWith")
    @ResponseBody
    public RspVo<String> dealWith(HttpServletRequest request, String srcBizSguid,
                                  String processId, String state, String dealIdea) {
        String[] fileAtt = request.getParameterValues("fileAtt");//附件
        wsFlowProcess.dealWith(srcBizSguid, processId, state, dealIdea, fileAtt);
        return RspVo.getSuccessResponse();
    }
    
    /**
     * 逻辑删除
     */
    @RequestMapping("/logicDel")
    @ResponseBody
    public RspVo<String> logicDel(HttpServletRequest request,String processId) {
        wsFlowProcess.logicDel(processId);
        return RspVo.getSuccessResponse();
    }

    /**
     * 上传审批附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "procNodeAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传审批录附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 生成 对应 跳转到各业务审核页面的controller方法
     * @param srcBizTable
     * @return 
     * @see
     */
    private String bizControllerMapping(String srcBizTable, String srcBizSguid) {
        StringBuilder result = new StringBuilder("redirect:/");
        // 如把PRO_MASTER_INFO 转成 masterInfo
        String[] split = srcBizTable.split("_");
        StringBuilder buffer = new StringBuilder();
        buffer.append(split[1].toLowerCase());
        if (StringUtils.equals("MKT_BID_REVIEW", srcBizTable)) {
            BidReview bidReview = bidReviewService.selectById(srcBizSguid);
            if (bidReview != null) {
                if (StringUtils.equals("1", bidReview.getBidType())) {
                    result.append("creditDetails/toDealOrDetail?id=");
                } else if (StringUtils.equals("2", bidReview.getBidType())) {
                    result.append("business/toDealOrDetail?id=");
                } else if (StringUtils.equals("3", bidReview.getBidType())) {
                    result.append("technicalDetail/toDealOrDetail?id=");
                }
                result.append(srcBizSguid);
                result.append("&processDealWith=y&proCode=");
                result.append(bidReview.getProCode());
                return result.toString();
            }
        }
        for (int i = 2; i < split.length; i++ ) {
            String lowerCaseSplit = split[i].toLowerCase();
            String firstUpperChar = (lowerCaseSplit.charAt(0) + "").toUpperCase();
            buffer.append(firstUpperChar + lowerCaseSplit.substring(1));
        }
        result.append(buffer);
        // 【注意】：所有业务表单，跳转到审核页面必须统一命名：toDealOrDetail
        String proCode = "";
        if (srcBizTable.startsWith("MKT_")) {
            try {
                proCode = proProcessManageService.getProCodeById(srcBizTable, srcBizSguid);
            } catch (Exception e) {

            }
        } else if (srcBizTable.startsWith("CAP_")) {
            try {
                proCode = capProcessManageService.getProCodeById(srcBizTable, srcBizSguid);
            } catch (Exception e) {

            }
        } else if (srcBizTable.startsWith("FIA_")) {
            try {
                proCode = fiaProcessManageService.getProCodeById(srcBizTable, srcBizSguid);
            } catch (Exception e) {

            }
        } else if (srcBizTable.startsWith("BPA_")) {
            try {
//                proCode = capProcessManageService.getProCodeById(srcBizTable, srcBizSguid);
            } catch (Exception e) {

            }
        }
        result.append("/toDealOrDetail?id=");
        result.append(srcBizSguid);
        result.append("&processDealWith=y&proCode=");
        result.append(proCode);
        return result.toString();
    }

}
